<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 报价单线路
 *
 */
class XBjline extends Backend
{
    /**
     * XBjline模型对象
     * @var \app\admin\model\XBjline
     */
    protected $model = null;
    protected $head= null;
    protected $cost=null;
    protected $code=null;
    protected $area=null;
    public $body=null;
    protected $quickSearchField = ['ID'];

    protected $defaultSortField = 'ID,desc';

    protected $preExcludeFields = [''];
    protected $noNeedLogin      = ['*'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XBjline;
        $this->head =new \app\admin\model\XBjhead();
        $this->cost =new \app\admin\model\XBjcost();
        $this->code =new \app\admin\model\Codelib();
        $this->area =new \app\admin\model\AREA();
        $this->body =new \app\admin\model\XBjbody();
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        //判断是常规还是线路
        $get=$this->request->get();
//        $get=['type'=>1,'bjno'=>'2101BJ0002'];
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $data=[];

        if($get['type']==1){
            $id=$this->model->where(['BJNO'=>$get['bjno']])->where("LOADPLACE IS NULL")->value('id');
            //判断是否有常规线路
            if($id){
                $sql="select CODELIB.CODENAME,X_BJLINE.ID as bid,
X_BJCOST.ID ,

 X_BJCOST.PRICETYPE,

 X_BJCOST.UNITPRICE,

 X_BJCOST.MONEYTYPE,

 X_BJCOST.TAXRATE,

 X_BJCOST.NOTAXPRICE,

 (CASE WHEN X_BJCOST.ITEMCODE='ZXF' THEN '租期' else '免费' end) AS TYPE,

 X_BJCOST.TRANSDAYS,

 CODELIB.REMIND,

 X_BJCOST.NOTE

from x_bjline as X_BJLINE,x_bjcost as X_BJCOST,codelib as CODELIB 

where X_BJLINE.ID=X_BJCOST.LINEID AND X_BJLINE.LOADPLACE IS NULL AND X_BJLINE.BJNO='$get[bjno]'

 AND X_BJCOST.ITEMCODE=CODELIB.CODE AND CODELIB.CODETYPE='cgbj'";
                $res=Db::query("$sql");
                //判断是否有常规线路

                $data= [
                    'id'=>$id,
                    'list'   => $res,
                    'total'  => count($res),
                    'remark' => get_route_remark(),
                ];
//                $res=$this->cost->where(['BJNO'=>$get['bjno'],'LINEID'=>$id])->paginate();
//                $data= [
//                    'list'   => $res->items(),
//                    'total'  => $res->total(),
//                    'remark' => get_route_remark(),
//                ];
            }else{
                $adminInfo          = $this->auth->getInfo();
                //没有就添加一条
                $add=[
                  'BJNO'=>$get['bjno'],
                    'NOTE'=>'',
                    'OP'=>$adminInfo['nickname'],
                    'OPTIME'=>date('Y-m-d H:i:s',time())
                ];
                $ids=$this->model->insertGetId($add);
                $data= [
                    'id'=>$ids,
                    'list'   => '',
                    'total'  =>'',
                    'remark' => '',
                ];
            }
        }
        else{
            $res = $this->model
                ->field('ID,LOADPLACE,DISPLACE,BJNO')
                ->with('cost')
                ->alias($alias)
                ->where($where)
                ->where(['BJNO'=>$get['bjno']])
                ->where('LOADPLACE','<>',' ')
                ->order($order)
                ->paginate($limit);
            $code=$this->code->where('codetype','itemcode')->column('CODENAME','CODE');

            $bjcosttype=$this->code->where('codetype','bjcosttype')->order('ATTR','desc')->column('CODENAME,ATTR','CODE');
            foreach ($res as $re) {
                $type=[];
                foreach ($re['cost'] as $k=>&$item) {
                    if(isset($code[$item['ITEMCODE']])){
                        $item['ITEMCODE']=$code[$item['ITEMCODE']];
                    }


                    $item['TRANSDAYS']=$this->convert_number( $item['TRANSDAYS']);
                    $item['UNITPRICE']=$this->convert_number( $item['UNITPRICE']);
                    $item['TAXRATE']=$this->convert_number( $item['TAXRATE']);
                    $item['NOTAXPRICE']=$this->convert_number( $item['NOTAXPRICE']);

                    if(isset($bjcosttype[$item['COSTTYPE']])){
                        $type[$item['COSTTYPE']]['list'][]=$item;
                        $type[$item['COSTTYPE']]['ATTR']=(int)$bjcosttype[$item['COSTTYPE']]['ATTR'];
                        $type[$item['COSTTYPE']]['CODENAME']=$bjcosttype[$item['COSTTYPE']]['CODENAME'];
                        $type[$item['COSTTYPE']]['day']=Db::query("select  sum(transdays) as day from x_bjcost where lineid='$re[ID]'   and bjno='$get[bjno]' and costtype='$item[COSTTYPE] '")[0]['day'];
                        $type[$item['COSTTYPE']]['costs']=Db::query("select  sum(case when costtype='GXZLCB' then unitprice * transdays else unitprice end) as costs  from x_bjcost where lineid='$re[ID]'   and bjno='$get[bjno]' and costtype='$item[COSTTYPE] '")[0]['costs'];
                        $type[$item['COSTTYPE']]['price']=Db::query("select  sum(case when costtype='GXZLCB' then notaxprice * transdays else notaxprice end) as price from x_bjcost where lineid='$re[ID]'   and bjno='$get[bjno]' and costtype='$item[COSTTYPE] '")[0]['price'];
                    }

                }
                $type=array_values($type);

                $attr=array_column($type,'ATTR');

                rsort($attr);
                array_multisort($attr,$type);

                $re['type']=$type;
                $re['day']=Db::query("select  sum(transdays) as day from x_bjcost where lineid='$re[ID]'  and bjno='$get[bjno]'   and costtype<>'GXZLCB' ")[0]['day'];
                $re['costs']=Db::query("select  sum(case when costtype='GXZLCB' then unitprice * transdays else unitprice end) as costs from x_bjcost where lineid='$re[ID]' and bjno='$get[bjno]' ")[0]['costs'];
                $re['price']=Db::query("select  sum(case when costtype='GXZLCB' then notaxprice * transdays else notaxprice end) as price from x_bjcost where lineid='$re[ID]' and bjno='$get[bjno]'")[0]['price'];
            }
            $data= [
                'list'   => $res->items(),
                'total'  => $res->total(),
                'remark' => get_route_remark(),
            ];
        }
        $this->success('',$data);
    }
    public function index_xl(){
        $get=$this->request->get('bjno');
        $data=$this->model->where("BJNO=$get and LOADPLACE is null ")->find();
        $this->success('成功',$data);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $adminInfo          = $this->auth->getInfo();
            $data['OP']=$adminInfo['nickname'];
            $data['OPTIME']=date('Y-m-d H:i:s',time());
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    /**
     * 关于起运地、目的地
     */
    public function ywtype(){
        $get=$this->request->get();
//        $bjno='2011BJ0001';
        if(isset($get['BJNO'])){
            if(!isset($get['PORT']))$get['PORT']='送货地';
            $head=$this->head->where('BJNO',$get['BJNO'])->find();
            $remind=[];
            if($head){
                if($head['YWTYPE']=='内贸'){
                    if($head['CORP']==''){
                        $this->success('自由输入','');
                    }else{
                        //查出送货地
                        $remind=$this->area->where(['CORP'=>$head['CORP'],'PORT'=>$get['PORT']])->column('remind');
                    }
                }else{
                    $remind=Db::table('port')->column('PORT');
                }
            }

            $this->success('',$remind);
        }

    }

    /**
     * 免费时间标签取值：
     */
    public function freevalue(){
        $xm=$this->request->get('name');

        $data=Db::query("select case when code='ZXF' THEN '租期' else '免费时间' end as time from codelib where code='$xm' and codetype='cgbj'");

        $this->success('',$data);
    }

    /**
     * 免费时间单位取值
     */
    public function freetime(){
        $xm=$this->request->get('name');
        $data=Db::query("select remind from codelib where code='$xm' and codetype='cgbj'");

        $this->success('',$data);
    }
    /**
     * 删除
     * @param array $ids
     */
    public function del(array $ids = [])
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
        }

        $pk    = $this->model->getPk();
        $id  = $this->request->param($this->model->getPk());
        //查询线路下有没有成本费用或者收入费用
        $cost=$this->cost->where('LINEID', 'in', $ids)->select();
        $body=$this->body->where('LINEID', 'in', $ids)->select();
        if($cost || $body){
            $this->error(' 此线路下还有成本费用（收入费用）不能删除。');
        }
        $data  = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($data as $v) {
                $count += $v->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }
}